package com.qifenqian.turbot.base

import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.net.ConnectivityManager
import android.os.Bundle
import android.os.Handler
import android.support.annotation.LayoutRes
import android.support.v7.app.AppCompatActivity
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.qifenqian.turbot.R
import com.qifenqian.turbot.config.NetReceiver
import com.qifenqian.turbot.util.Lcat
import com.qifenqian.turbot.util.NetUtils
import com.qifenqian.turbot.util.StringUtils
import kotlinx.android.synthetic.main.layout_error.view.*
import org.jetbrains.anko.toast

/**
 * @author H
 * @createDate 2018/8/9 12:03
 * @reference
 * @updateDate
 * @description
 * @detail
 * @since
 */
abstract class BaseActivity<P : BasePresenter<V, *>, V> : AppCompatActivity() {

    protected var mPresenter: P? = null
    protected var mReceiver: NetReceiver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        Lcat.d("当前Activity", javaClass.simpleName)
        setContentView(bindLayoutId())
        mPresenter = bindPresenter()
        initial()
    }

    /**
     * 判断当前是否有网络,点击事件等调用
     */
    fun isNetworkConnected(): Boolean {
        if (!NetUtils.isNetworkAvailable(this)) {
            toast("没有网络")
            return false
        }
        return true
    }

    @LayoutRes
    abstract fun bindLayoutId(): Int

    abstract fun bindPresenter(): P?

    abstract fun initial()

    override fun onResume() {
        super.onResume()
        if (mPresenter != null) {
            mPresenter!!.attachView(this as V)
        }
    }

    override fun onStart() {
        super.onStart()
        registerNetworkReceiver()
    }

    private fun registerNetworkReceiver() {
        mReceiver = NetReceiver()
        val filter = IntentFilter()
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(mReceiver, filter)
    }

    override fun onStop() {
        super.onStop()
        //防止程序在后台的时候也接收到网络变化的广播
        unregisterReceiver(mReceiver)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mPresenter != null) {
            mPresenter!!.detachView()
        }
    }

    fun showErrorPage(onClickListener: View.OnClickListener?, msg: String? = "错误", attachToRoot: Boolean = true) {
        val lyContent = findViewById<ViewGroup>(R.id.ly_content)
        lyContent.removeAllViews()
        val view = LayoutInflater.from(this).inflate(R.layout.layout_error, lyContent, attachToRoot)
        view.tv_error_message.text = msg
        view.btn_error_retry.setOnClickListener {
            onClickListener?.onClick(view.btn_error_retry)
        }
    }

    /**
     * @see //blog.csdn.net/qq_33703877/article/details/77461280
     */
    protected fun TextView.setSpannableText(s: String, lightText: String, onClickListener: View.OnClickListener?) {
        val spannableString = SpannableString(s)
        spannableString.setSpan(object : ClickableSpan() {
            override fun onClick(view: View) {
                onClickListener?.onClick(view)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = resources.getColor(R.color.blue_e60080ff)
                ds.isUnderlineText = false
            }
        }, s.indexOf(lightText), s.indexOf(lightText) + lightText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        movementMethod = LinkMovementMethod.getInstance()
        highlightColor = resources.getColor(R.color.transparent)
        text = spannableString
    }

    protected fun finishDelay() {
        Handler().postDelayed({ this.finish() }, 500)
    }

    protected fun TextView.removeHanziAndLetters(): String {
        val sb = StringBuilder()
        if (!text.isNullOrBlank()) {
            for (c in text.toString()) {
                if (!StringUtils.isHanzi(c.toString()) && !StringUtils.isLetter(c.toString())) {
                    sb.append(c)
                }
            }
            return sb.toString().trim()
        } else {
            return "0"
        }
    }
}